from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.services.product_service import ProductService
from app.models.product import Product
from app import db
from sqlalchemy import func

products_bp = Blueprint('products', __name__)
product_service = ProductService()

@products_bp.route('/products', methods=['GET', 'OPTIONS'])
def get_products():
    # 获取查询参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    category = request.args.get('category')
    search = request.args.get('search')
    
    # 构建查询
    query = Product.query
    
    # 按分类筛选
    if category:
        query = query.filter(Product.category == category)
    
    # 搜索功能
    if search:
        query = query.filter(
            (Product.name.ilike(f'%{search}%')) | 
            (Product.description.ilike(f'%{search}%'))
        )
    
    # 分页
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    products = pagination.items
    
    return jsonify({
        'products': [{
            'id': str(p.id),
            'name': p.name,
            'description': p.description,
            'price': p.price,
            'imageUrl': p.image_url,
            'stock': p.stock,
            'category': p.category,
            'discount': p.discount
        } for p in products],
        'total': pagination.total,
        'pages': pagination.pages,
        'current_page': page
    }), 200

@products_bp.route('/products/categories', methods=['GET'])
def get_categories():
    # 获取所有分类
    categories = db.session.query(Product.category).distinct().all()
    
    return jsonify({
        'categories': [category[0] for category in categories if category[0]]
    }), 200

@products_bp.route('/<int:product_id>', methods=['GET'])
def get_product(product_id):
    product = product_service.get_product_by_id(product_id)
    return jsonify(product)

@products_bp.route('/', methods=['POST'])
@jwt_required()
def create_product():
    data = request.get_json()
    result = product_service.create_product(data)
    return jsonify(result)

@products_bp.route('/<int:product_id>', methods=['PUT'])
@jwt_required()
def update_product(product_id):
    data = request.get_json()
    result = product_service.update_product(product_id, data)
    return jsonify(result)

@products_bp.route('/<int:product_id>', methods=['DELETE'])
@jwt_required()
def delete_product(product_id):
    result = product_service.delete_product(product_id)
    return jsonify(result) 